package com.baoxin.chenxixc4coach;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Environment;
import android.os.SystemClock;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.TextView;

import com.baoxin.chenxixc4coach.dialog.AudioEditDialog;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;

import static android.media.MediaRecorder.AudioEncoder.AAC;
import static android.media.MediaRecorder.AudioSource.MIC;
import static android.media.MediaRecorder.OutputFormat.MPEG_4;

/**
 * 语音录制
 */
public class AudioRecordActivity extends BaseActivity implements View.OnClickListener {


    private ImageView mStop;
    private ImageView mStart;
    private ImageView mDelete;
    private Chronometer mTimer;

    //录音状态
    private enum State {
        NON_RECORDING, RECORDING
    }

    private State state;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_audio_record);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //请求权限
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.RECORD_AUDIO, Manifest.permission.READ_EXTERNAL_STORAGE}, 1);

        mStop = findViewById(R.id.stop);
        mStart = findViewById(R.id.start_record);
        mDelete = findViewById(R.id.delete);
        mTimer = findViewById(R.id.timer);

        mStart.setOnClickListener(this);
        mStop.setOnClickListener(this);
        mDelete.setOnClickListener(this);

        state = State.NON_RECORDING;

    }

    private MediaRecorder mr;
    /**
     * 当前录音文件存放的路径
     */
    private String filePath;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.start_record:
                startRecord();
                break;
            case R.id.stop:
                stopRecord();
                break;
            case R.id.delete:
                deleteRecord();
                break;
        }
    }

    /**
     * 开始录制
     */
    private void startRecord() {
        if (state == State.NON_RECORDING) {
            mr = new MediaRecorder();
            mr.setAudioSource(MIC);
            mr.setOutputFormat(MPEG_4);
            mr.setAudioEncoder(AAC);
            String fileName = DateFormat.format("yyyyMMddHHmmss", Calendar.getInstance()) + ".m4a";

            filePath = getAudioDir(this) + File.separator + fileName;
            mr.setOutputFile(filePath);
            try {
                mr.prepare();
                mr.start();
                state = State.RECORDING;
                mStart.setImageResource(R.drawable.record_pause);
                mStop.setImageResource(R.drawable.record_stop_2);
                mDelete.setImageResource(R.drawable.record_delete);
                mTimer.setBase(SystemClock.elapsedRealtime());
                int hour = (int) ((SystemClock.elapsedRealtime() - mTimer.getBase()) / 1000 / 60);
                mTimer.setFormat("0" + String.valueOf(hour) + ":%s");
                mTimer.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {

        }


    }


    /**
     * 停止录音
     */
    private void stopRecord() {
        if (state == State.RECORDING) {
            mr.stop();
            mr.release();
            mr = null;
            state = State.NON_RECORDING;
            mStart.setImageResource(R.drawable.record_start);
            mStop.setImageResource(R.drawable.record_stop);
            mDelete.setImageResource(R.drawable.record_delete_2);
            AudioEditDialog editDialog = new AudioEditDialog();
            editDialog.show(getSupportFragmentManager(), filePath);
            mTimer.stop();
        }
    }

    /**
     * 删除录音
     */
    private void deleteRecord() {
        File file = new File(filePath);
        file.delete();
        mDelete.setImageResource(R.drawable.record_delete);
        mTimer.setText("00:00:00");
    }


    public static String getAudioDir(Context context) {
        String directoryPath = "";
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {//判断外部存储是否可用
            directoryPath = context.getExternalFilesDir("audio_course").getAbsolutePath();
        } else {//没外部存储就使用内部存储
            directoryPath = context.getFilesDir() + File.separator + "audio_course";
        }
        File file = new File(directoryPath);
        if (!file.exists()) {//判断文件目录是否存在
            file.mkdirs();
        }
        return directoryPath;
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

        } else {
            showMissingPermissionDialog();
        }
    }
}
